package com.youdianstar.app.common.base

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Observer
import com.youdianstar.app.common.callback.NetworkStateManager
import com.youdianstar.app.common.util.ToastUtil


/**
 * File: BaseFragment
 * Author: 82149 Create: 2021/9/22 15:08
 * Changes (from 2021/9/22)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
abstract class BaseFragment<DB : ViewDataBinding,VM : BaseViewModel> : BaseBMFragment<DB, VM>(){

    abstract override fun initVariableId(): Int

    abstract override fun initContentView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): Int

    abstract override fun initData()
    abstract override fun initClickEvent()
    abstract override fun initLiveObserver()

    private val handler = Handler(Looper.myLooper()!!)
    //是否第一次加载
    private var isFirst: Boolean = true

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

    /**
     * 懒加载
     */
    fun lazyLoadData(){

    }

    open fun lazyLoadTime(): Long {
        return 300
    }

    open fun onNetworkStateChanged(isConnect: Boolean) {}

    override fun onResume() {
        super.onResume()
        onVisible()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }

    /**
     * 是否需要懒加载
     */
    private fun onVisible() {
        if (lifecycle.currentState == Lifecycle.State.STARTED && isFirst) {
            // 延迟加载 防止 切换动画还没执行完毕时数据就已经加载好了，这时页面会有渲染卡顿
            handler.postDelayed( {
                lazyLoadData()
                //在Fragment中，只有懒加载过了才能开启网络变化监听
                NetworkStateManager.instance.mNetworkStateCallback.observe(this, Observer {
                        if (!isFirst) { //不是首次订阅时调用方法，防止数据第一次监听错误
                            onNetworkStateChanged(it)
                        }
                    })
                isFirst = false
            },lazyLoadTime())
        }
    }

    /**
     * toast
     *
     * @param text
     */
    fun toastShow(text: String?, type: Int = 0) {
        if (TextUtils.isEmpty(text))
            return
        val prefix = if (type == 1) "AT-" else ""
        ToastUtil.show(activity,"$prefix$text")
    }
}